package com.lening.common.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 牛强
 * @datetime 2024/4/22 14:42
 * @description 数据转换工具类（jwt添加载荷信息用到）
 */
public final class ConvertUtil {
    /**
     * 实体类转map
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> toMap(T t) {
        Map<String, Object> result = new HashMap<>();

        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            try {
                Object object = field.get(t);
                result.put(name, object);
            } catch (IllegalAccessException | IllegalArgumentException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }
}
